package cms

import (
	"context"
	"gitcode.com/G-YT/baoyou/server/global"
	"gitcode.com/G-YT/baoyou/server/model/cms"
	cmsReq "gitcode.com/G-YT/baoyou/server/model/cms/request"
	"gitcode.com/G-YT/baoyou/server/utils"
	"gorm.io/datatypes"
	"strconv"
)

type ArticleService struct{}

// CreateArticle 创建文章信息记录
// Author [yourname](https://github.com/yourname)
func (articleService *ArticleService) CreateArticle(ctx context.Context, article *cms.Article) (err error) {
	err = global.GVA_DB.Create(article).Error
	return err
}

// DeleteArticle 删除文章信息记录
// Author [yourname](https://github.com/yourname)
func (articleService *ArticleService) DeleteArticle(ctx context.Context, ID string) (err error) {
	err = global.GVA_DB.Delete(&cms.Article{}, "id = ?", ID).Error
	return err
}

// DeleteArticleByIds 批量删除文章信息记录
// Author [yourname](https://github.com/yourname)
func (articleService *ArticleService) DeleteArticleByIds(ctx context.Context, IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]cms.Article{}, "id in ?", IDs).Error
	return err
}

// UpdateArticle 更新文章信息记录
// Author [yourname](https://github.com/yourname)
func (articleService *ArticleService) UpdateArticle(ctx context.Context, article cms.Article) (err error) {
	err = global.GVA_DB.Model(&cms.Article{}).Where("id = ?", article.ID).Updates(&article).Error
	return err
}

// GetArticle 根据ID获取文章信息记录
// Author [yourname](https://github.com/yourname)
func (articleService *ArticleService) GetArticle(ctx context.Context, ID string) (article cms.Article, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&article).Error
	var currentViews int64 = 0
	if article.Views != nil {
		currentViews = *article.Views
	}
	article.Views = utils.Pointer(currentViews + 1)
	global.GVA_DB.Model(&cms.Article{}).Where("id = ?", article.ID).Update("views", article.Views)
	return
}

// GetArticleInfoList 分页获取文章信息记录
// Author [yourname](https://github.com/yourname)
func (articleService *ArticleService) GetArticleInfoList(ctx context.Context, info cmsReq.ArticleSearch) (list []cms.Article, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&cms.Article{})
	var articles []cms.Article
	// 如果有条件搜索 下方会自动创建搜索语句
	if len(info.CreatedAtRange) == 2 {
		db = db.Where("created_at BETWEEN ? AND ?", info.CreatedAtRange[0], info.CreatedAtRange[1])
	}

	if info.Author != nil && *info.Author != "" {
		db = db.Where("author LIKE ?", "%"+*info.Author+"%")
	}
	if info.VIP != nil {
		db = db.Where("vip = ?", *info.VIP)
	}

	if info.Type != nil {
		db = db.Where("type = ?", *info.Type)
	}

	if info.Title != nil {
		db = db.Where("title LIKE ?", "%"+*info.Title+"%")
	}

	if info.Status != nil {
		db = db.Where("status = ?", *info.Status)
	}

	// 按分类搜索（包含子分类）
	if info.Category != nil && *info.Category != "" {
		var categoryIDS []uint
		cateId, err := strconv.Atoi(*info.Category)
		if err == nil {
			cates, _ := cateser.GetCategoryDeep(ctx, uint(cateId))
			for i := range cates {
				categoryIDS = append(categoryIDS, cates[i].ID)
			}
			if len(categoryIDS) > 0 {
				db = db.Where("category IN ?", categoryIDS)
			}
		}
	}

	// 按标签搜索
	if info.Tags != nil && *info.Tags != "" {
		db = db.Where("JSON_CONTAINS(tags, ?)", datatypes.JSON("["+*info.Tags+"]"))
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}
	var OrderStr string
	orderMap := make(map[string]bool)
	orderMap["id"] = true
	orderMap["created_at"] = true
	orderMap["title"] = true
	orderMap["price"] = true
	orderMap["repost"] = true
	orderMap["views"] = true
	if orderMap[info.Sort] {
		OrderStr = info.Sort
		if info.Order == "descending" {
			OrderStr = OrderStr + " desc"
		}
		db = db.Order(OrderStr)
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&articles).Error
	return articles, total, err
}
func (articleService *ArticleService) GetArticleDataSource(ctx context.Context) (res map[string][]map[string]any, err error) {
	res = make(map[string][]map[string]any)
	category := make([]map[string]any, 0)

	global.GVA_DB.Table("by_cms_categories").Where("deleted_at IS NULL").Select("name as label,id as value").Scan(&category)
	res["category"] = category
	tags := make([]map[string]any, 0)

	global.GVA_DB.Table("by_cms_tag").Where("deleted_at IS NULL").Select("name as label,id as value").Scan(&tags)
	res["tags"] = tags
	return
}
func (articleService *ArticleService) GetArticlePublic(ctx context.Context) {
	// 此方法为获取数据源定义的数据
	// 请自行实现
}

func (articleService *ArticleService) GetArticleByTag(ctx context.Context, tag string) (articles []cms.Article, err error) {
	db := global.GVA_DB.Model(&cms.Article{})
	db = db.Where("JSON_CONTAINS(tags, ?)", datatypes.JSON("["+tag+"]"))
	err = db.Find(&articles).Error
	return
}

var cateser = new(CategoryService)

func (articleService *ArticleService) GetArticleByCate(ctx context.Context, cate string) (articles []cms.Article, err error) {
	var categoryIDS []uint

	cateId, _ := strconv.Atoi(cate)

	cates, err := cateser.GetCategoryDeep(ctx, uint(cateId))
	for i := range cates {
		categoryIDS = append(categoryIDS, cates[i].ID)
	}

	err = global.GVA_DB.Model(&cms.Article{}).Where("category_id IN ?", categoryIDS).Find(&articles).Error

	return
}
